# coding = utf-8
# Author = Ann
# Date: 2023/6/27
import logging

from selenium.common import NoSuchElementException

from tools.reader.parser_reader import element_reader, excel_reader


class ElementsLookUp:

    @classmethod
    def element_lookup(cls, driver, element_name):
        """
        :param driver: WebDriver instance
        :param element_name: Name of the element to lookup
        """
        logger = logging.getLogger()  # 获取当前模块的日志记录器
        element_dict = element_reader()  # 调用element_reader函数获取元素字典
        for i in element_dict:
            if i["name"] == element_name:
                by_type = i["lookupDetails"]["findBy"]
                value = i["lookupDetails"]["value"]
                try:
                    element = driver.find_element(by_type, value)
                    return element
                except AttributeError as e:
                    logger.error(f"Error! No support for {by_type.capitalize()} type")
                    continue  # 跳过当前循环迭代，尝试查找下一个元素
        else:
            logger.error("No such element!")
            raise NoSuchElementException("The element cannot be found!")

    @classmethod
    def get_element_details(cls, element_name):
        """
        :param element_name:
        """
        logger = logging.getLogger()
        element_dict = element_reader()
        for i in element_dict:
            if i["name"] == element_name:
                try:
                    element_find_type = i["lookupDetails"]["findBy"]
                    element_value = i["lookupDetails"]["value"]
                    return element_find_type, element_value
                except AttributeError as e:
                    continue
        else:
            logger.error("No such element!")
            raise NoSuchElementException("The element cannot be found!")

    @classmethod
    def data_lookup(cls, file_name, sheet_name, role, role_value, name):
        """
        :param file_name:
        :param sheet_name: Name of Sheet
        :param role: Name of the first line
        :param role_value: Value of the first line
        :param name: Value wanna return
        """
        excel_dict = excel_reader(file_name, sheet_name)
        try:
            for i in excel_dict:
                if i[role] == int(role_value):
                    data_name = i[name]
                    return data_name
        except Exception as e:
            raise e
